﻿using Approval.API.Applcation.Command.RLZRelationCommand;
using Approval.Domain;
using Approval.Infrastructure.Impl;
using Approval.Infrastructure.Interface;
using MediatR;

namespace Approval.API.Applcation.CommandHandler.RLZRelationCommandHandler
{
    public class RLZRelationCreateCommandHandler : IRequestHandler<RLZRelationCreateCommand, int>
    {
        private readonly IRLZRelationRepository rLZRelationRepository;

        public RLZRelationCreateCommandHandler(IRLZRelationRepository rLZRelationRepository)
        {
            this.rLZRelationRepository = rLZRelationRepository;
        }

        public async Task<int> Handle(RLZRelationCreateCommand request, CancellationToken cancellationToken)
        {
            var list = await rLZRelationRepository.GetInfo(x=>x.RLZId == request.RLZId &&x.ApprovalState==3 );
            if (list!= null)
            {
                await rLZRelationRepository.Delete(list.Id);
            }
            //默认第一次提交付款审批是彭于晏
            var hctRelation = new RLZRelation()
            {
                RLZId = request.RLZId,
                ApprovalId = request.ApprovalId != 0 ? request.ApprovalId : 4,
                ApprovalName = (request.ApprovalName == "") ? request.ApprovalName : "彭于晏",
                ApprovalDesc = null
            };
            var res = await rLZRelationRepository.Create(hctRelation);
            return res;
        }
    }
}
